﻿///***************************************************************
/// 시  스  템 : Updms.Mny
/// 단위시스템 : MNy
/// 계      층 : Presentation Layer
/// 프로그램명 : Mny4011b
/// 파  일  명 : Mny4011b.aspx.cs
/// 설      명 : 월마감처리
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2010-07-30 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using SMFramework.Data;
using SMFramework.Utility;

using Base.Dac;
using Updms.Mny.Exe;


namespace Updms.Mny
{
	public partial class Mny4011b : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Mny4011b";
		public static readonly string gs_path_info = "/updms/Mny/" + PID + ".aspx";

		Global global = new Global();

		//검색
		protected string kw1 = "";	// 검색1
		protected string kw2 = "";	// 검색2
		protected string kw3 = "";	// 검색3

		// 페이지모드
		
		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SearchProcess();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetClientScript();
			SetYearMonth();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion

		#region SetClientScript

		private void SetClientScript()
		{
			//onKeyUp이벤트
			txt_bank_amount_1.Attributes.Add("onkeyup", "document.form1.txt_bank_amount_1.value=addComma(document.form1.txt_bank_amount_1.value);calcInterest('1');");
			txt_bank_amount_2.Attributes.Add("onkeyup", "document.form1.txt_bank_amount_2.value=addComma(document.form1.txt_bank_amount_2.value);calcInterest('2');");
			txt_bank_amount_3.Attributes.Add("onkeyup", "document.form1.txt_bank_amount_3.value=addComma(document.form1.txt_bank_amount_3.value);calcInterest('3');");
			txt_bank_amount_4.Attributes.Add("onkeyup", "document.form1.txt_bank_amount_4.value=addComma(document.form1.txt_bank_amount_4.value);calcInterest('4');");
			txt_bank_amount_5.Attributes.Add("onkeyup", "document.form1.txt_bank_amount_5.value=addComma(document.form1.txt_bank_amount_5.value);calcInterest('5');");
		}

		#endregion

		#region SetInit, SetSearchParameter, ShowKeywordLabel

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
					{
						kw1 = ddl_year.SelectedValue + "-" + ddl_month.SelectedValue;
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						ddl_year.SelectedValue = kw1.Substring(0, 4).ToString();
						ddl_month.SelectedValue = kw1.Substring(5, 2).ToString();
					}
					break;
				case "SEARCH":
					kw1 = ddl_year.SelectedValue + "-" + ddl_month.SelectedValue;
					break;
			}
		}

		//검색키워드
		private void ShowKeywordLabel()
		{
		}

		#endregion

		#region 디테일 Method (SetYearMonth)

		// 검색조건의 년월설정
		private void SetYearMonth()
		{
			ddl_year.Items.Clear();

			int li_f_year = Convert.ToInt32(DateUtil.GetYearEx(-1, "yyyy"));
			int li_t_year = Convert.ToInt32(DateUtil.GetYearEx(1, "yyyy"));
			for (int i = li_f_year; i <= li_t_year; i++)
			{
				string ls_year = i.ToString();
				ddl_year.Items.Add(new ListItem(ls_year, ls_year));
			}

			ddl_year.SelectedValue = DateUtil.GetNow("yyyy"); // 현재년
			ddl_month.SelectedValue = DateUtil.GetNow("MM"); // 현재월
		}
				
		#endregion

		#region CRUD (SelectProcess, InsertProcess, DeleteProcess, SearchProcess)

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			
			int li_balance = 0;
			
			using (Mny4011b_NT _Mny4011b_NT = new Mny4011b_NT())
			{
				lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);
				lo_ds.Merge(_Mny4011b_NT.GetAccountOnMonthlyClose(lo_dp));
				
				lo_dp.RemoveProperty("ls_lang_set");
				lo_dp.AddProperty("ls_base_ym", typeof(string), kw1);				
				li_balance = _Mny4011b_NT.GetMonthlyBalance(lo_dp);
			}
			
			int row_count = DataSetUtil.GetRowCount(lo_ds, "UPDMS_MNY_BATCH");
			h_total_row_count.Value = row_count.ToString();
			
			if (row_count > 0)
			{
				if (row_count > 5)
				{
					CallMsgBoxInAjax("MSG_ERR_153");	//처리 가능한 계정의 수를 초과하였습니다(5개 까지 처리 가능)
				}
				else
				{
					for (int i = 0; i < row_count; i++)
					{
						HtmlInputHidden lbl_account = (HtmlInputHidden)Page.FindControl("lbl_account_" + (i + 1));
						Label lbl_account_nm = (Label)Page.FindControl("lbl_account_nm_" + (i + 1));
						Label lbl_curr_amount = (Label)Page.FindControl("lbl_curr_amount_" + (i + 1));

						lbl_account.Value = DataSetUtil.GetFldStr(lo_ds, "UPDMS_MNY_BATCH", i, "Account");
						lbl_account_nm.Text = DataSetUtil.GetFldStr(lo_ds, "UPDMS_MNY_BATCH", i, "Account_Nm");
						lbl_curr_amount.Text = ConversionUtil.AddComma(DataSetUtil.GetFldStr(lo_ds, "UPDMS_MNY_BATCH", i, "Total_Amount"));
					}

					//갯수만큼의 콘트롤만 Visible처리.나머지는 Invisible
					for (int j = 1; j <= 5; j++)
					{
						HtmlInputCheckBox cb = (HtmlInputCheckBox)Page.FindControl("cb_check_" + j);
						HtmlInputHidden lbl_account = (HtmlInputHidden)Page.FindControl("lbl_account_" + j);
						TextBox txt_bank_amount = (TextBox)Page.FindControl("txt_bank_amount_" + j);
						TextBox txt_interest = (TextBox)Page.FindControl("txt_interest_" + j);

						//TR
						HtmlTableRow tr = (HtmlTableRow)Page.FindControl("tr_" + j);

						if (lbl_account.Value.Length > 0)
						{
							cb.Checked = true;
							cb.Disabled = false;
							txt_bank_amount.Enabled = true;
							txt_interest.Enabled = true;
							tr.Visible = true;
						}
						else
						{
							cb.Checked = false;
							cb.Disabled = true;
							txt_bank_amount.Enabled = false;
							txt_interest.Enabled = false;
							tr.Visible = false;
						}
					}
				}
			}
			else
			{
				//전부 숨김
				for (int k = 1; k <= 5; k++)
				{
					HtmlTableRow tr = (HtmlTableRow)Page.FindControl("tr_" + k);
					tr.Visible = false;
				}

				//no data
				HtmlTableRow tr_nodata = new HtmlTableRow();
				HtmlTableCell td_nodata = new HtmlTableCell();
				
				td_nodata.ColSpan = 5;
				td_nodata.Attributes.Add("class", "ctl");
				td_nodata.InnerHtml = "<div id=\"no_data\"></div>";

				tr_nodata.Cells.Add(td_nodata);
				tbl_save.Rows.Add(tr_nodata);
			}
			
			//월별잔액
			txt_monthly_balance.Text = ConversionUtil.AddComma(li_balance.ToString());
		}

		//저장
		private void InsertProcess(string ls_xml)
		{
			using (Mny4011b_RT _Mny4011b_RT = new Mny4011b_RT())
			{
				int li_return = _Mny4011b_RT.InsertProcess(ls_xml);
				string ls_msg_id = (li_return > 0) ? "MSG_INF_016" : "MSG_ERR_154";	//마감되었습니다:마감할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);
			}
		}

		//마감취소
		private void DeleteProcess(string ls_base_ym)
		{
			using (Mny4011b_RT _Mny4011b_RT = new Mny4011b_RT())
			{
				int li_return = _Mny4011b_RT.DeleteProcess(ls_base_ym);
				string ls_msg_id = (li_return > 0) ? "MSG_INF_019" : "MSG_ERR_066";	//마감취소되었습니다:마감취소할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);
			}
		}

		//검색
		private void SearchProcess()
		{
			SetSearchParameter();
			ClearValue();
			SelectProcess();
		}

		#endregion

		#region SetValue, ClearValue

		//SetValue
		private string SetValue()
		{
			StringBuilder sb = new StringBuilder();

			//지정월의 마지막날
			string ls_ym = ddl_year.SelectedValue + "-" + ddl_month.SelectedValue;
			string ls_last_day = DateUtil.GetLastDay(ls_ym);
			string ls_reg_dt = ls_ym + "-" + ls_last_day;
			
			//지정월의 다음월 1일
			string ls_next_dt = DateUtil.GetCalcMonth(ls_reg_dt, 1, "yyyy-MM") +"-01";

			sb.Append("<UPDMS>");

			for (int i = 0; i < Convert.ToInt32(h_total_row_count.Value); i++)
			{
				HtmlInputCheckBox cb = (HtmlInputCheckBox)Page.FindControl("cb_check_" + (i + 1));

				HtmlInputHidden lbl_account = (HtmlInputHidden)Page.FindControl("lbl_account_" + (i + 1));
				Label lbl_account_nm = (Label)Page.FindControl("lbl_account_nm_" + (i + 1));
				TextBox txt_interest = (TextBox)Page.FindControl("txt_interest_" + (i + 1));

				string ls_interest = ConversionUtil.RemoveComma(txt_interest.Text);

				//이자 - 기준월로 수입, 저축 처리 (이자가 0이면 저장하지 않음)
				if (cb.Checked && ls_interest != "0")
				{
					//수입
					sb.Append("<UPDMS_MNY_IN_OUT_MGT>");
					sb.Append("<Reg_Dt>" + ls_reg_dt + "</Reg_Dt>");
					sb.Append("<Class>AA001</Class>");
					sb.Append("<Account>AB007</Account>");
					sb.Append("<Contents><![CDATA[" + lbl_account_nm.Text + " 이자" + "]]></Contents>");
					sb.Append("<Amount>" + ls_interest + "</Amount>");
					sb.Append("<Remark>-</Remark>");
					sb.Append("<Close_Yn>Y</Close_Yn>");
					sb.Append("<Create_User>" + USER_ID + "</Create_User>");
					sb.Append("<Update_User>" + USER_ID + "</Update_User>");
					sb.Append("</UPDMS_MNY_IN_OUT_MGT>");

					//저축
					sb.Append("<UPDMS_MNY_IN_OUT_MGT>");
					sb.Append("<Reg_Dt>" + ls_reg_dt + "</Reg_Dt>");
					sb.Append("<Class>AA003</Class>");
					sb.Append("<Account>" + lbl_account.Value + "</Account>");
					sb.Append("<Contents><![CDATA[" + "이자" + "]]></Contents>");
					sb.Append("<Amount>" + ls_interest + "</Amount>");
					sb.Append("<Remark>-</Remark>");
					sb.Append("<Close_Yn>Y</Close_Yn>");
					sb.Append("<Create_User>" + USER_ID + "</Create_User>");
					sb.Append("<Update_User>" + USER_ID + "</Update_User>");
					sb.Append("</UPDMS_MNY_IN_OUT_MGT>");
				}
			}

			//잔액 - 기준월 지출 처리
			sb.Append("<UPDMS_MNY_IN_OUT_MGT>");
			sb.Append("<Reg_Dt>" + ls_reg_dt + "</Reg_Dt>");
			sb.Append("<Class>AA002</Class>");
			sb.Append("<Account>AC996</Account>");
			sb.Append("<Contents><![CDATA[" + "잔액 차월이월" + "]]></Contents>");
			sb.Append("<Amount>" + ConversionUtil.RemoveComma(txt_monthly_balance.Text) + "</Amount>");
			sb.Append("<Remark>-</Remark>");
			sb.Append("<Close_Yn>Y</Close_Yn>");
			sb.Append("<Create_User>" + USER_ID + "</Create_User>");
			sb.Append("<Update_User>" + USER_ID + "</Update_User>");
			sb.Append("</UPDMS_MNY_IN_OUT_MGT>");

			//잔액 - 기준차월 수입 처리
			sb.Append("<UPDMS_MNY_IN_OUT_MGT>");
			sb.Append("<Reg_Dt>" + ls_next_dt + "</Reg_Dt>");
			sb.Append("<Class>AA001</Class>");
			sb.Append("<Account>AB996</Account>");
			sb.Append("<Contents><![CDATA[" + "잔액 전월이월" + "]]></Contents>");
			sb.Append("<Amount>" + ConversionUtil.RemoveComma(txt_monthly_balance.Text) + "</Amount>");
			sb.Append("<Remark>-</Remark>");
			sb.Append("<Close_Yn>Y</Close_Yn>");
			sb.Append("<Create_User>" + USER_ID + "</Create_User>");
			sb.Append("<Update_User>" + USER_ID + "</Update_User>");
			sb.Append("</UPDMS_MNY_IN_OUT_MGT>");
			
			sb.Append("</UPDMS>");

			//Base.AppFramework.SMEventLog.WriteDataLog("Mny4011b.InsertProcess", sb.ToString());
			
			return sb.ToString();
		}

		//ClearValue
		private void ClearValue()
		{
			txt_bank_amount_1.Text = "";
			txt_bank_amount_2.Text = "";
			txt_bank_amount_3.Text = "";
			txt_bank_amount_4.Text = "";
			txt_interest_1.Text = "";
			txt_interest_2.Text = "";
			txt_interest_3.Text = "";
			txt_interest_4.Text = "";
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_POPUP);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					//PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
		}


		#endregion		

		#region 버튼이벤트

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();
			ClearValue();
			SearchProcess();
		}

		//저장
		protected void ibtn_finish_Click(object sender, EventArgs e)
		{
			InsertProcess(SetValue());
		}

		//취소
		protected void ibtn_cancel_Click(object sender, EventArgs e)
		{
			DeleteProcess(ddl_year.SelectedValue + "-" + ddl_month.SelectedValue);
		}

		#endregion

	}
}
